package com.zy.service.bs.impl;

import com.zy.dao.bs.CarDao;
import com.zy.dao.bs.CustomerClubDao;
import com.zy.dao.bs.MsgDao;
import com.zy.dao.crm.CustomerApplyDao;
import com.zy.dao.crm.CustomerDao;
import com.zy.dao.crm.CustomerInfoDao;
import com.zy.dao.sys.UserDao;
import com.zy.dao.sys.UserRoleDao;
import com.zy.entity.bs.Car;
import com.zy.entity.bs.CustomerClub;
import com.zy.entity.bs.Msg;
import com.zy.entity.crm.Customer;
import com.zy.entity.crm.CustomerInfo;
import com.zy.entity.enums.bs.CheckStatusEnum;
import com.zy.entity.sys.User;
import com.zy.entity.sys.UserRole;
import com.zy.pojo.constants.Constant;
import com.zy.pojo.exceptions.ServiceException;
import com.zy.pojo.query.crm.CustomerApplyQuery;
import com.zy.utils.CodeUtil;
import com.zy.utils.MD5Util;
import com.zy.utils.PropertiesUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zy.entity.enums.StatusEnum;
import com.zy.entity.bs.CustomerApply;
import com.zy.pojo.vos.common.PageVo;
import com.zy.service.base.impl.BaseServiceImpl;
import com.zy.service.bs.CustomerApplyService;
import com.zy.utils.DateUtil;
import tk.mybatis.mapper.entity.Example;

import java.util.Objects;

@Service("customerApplyService")
public class CustomerApplyServiceImpl extends BaseServiceImpl<CustomerApply> implements CustomerApplyService {

	@Autowired
	private CustomerApplyDao customerApplyDao;
    @Autowired
    private MsgDao msgDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private CustomerInfoDao customerInfoDao;
    @Autowired
    private CarDao carDao;
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private CustomerClubDao customerClubDao;

	@Override
	public PageVo pageCustomerApply(CustomerApplyQuery customerApplyQuery, Integer start, Integer limit) {
		return new PageVo(start, limit, this.customerApplyDao.countCustomerApply(customerApplyQuery), this.customerApplyDao.listCustomerApply(customerApplyQuery, start, limit));
	}

	@Override
	public void saveCustomerApply(CustomerApply customerApply) {
		long time = DateUtil.getTime();

		this.customerApplyDao.save(customerApply);
	}
	
	@Override
	public void updateCustomerApply(CustomerApply customerApply) {
		this.customerApplyDao.updateByPrimaryKeySelective(customerApply);
	}

	@Override
	public void removeCustomerApply(long id) {
		try {
			this.customerApplyDao.removeByPrimaryKey(id);
		} catch (Exception e) {
			log.info(e.getMessage(),e);
			CustomerApply customerApply = new CustomerApply();
			customerApply.setId(id);
			this.customerApplyDao.updateByPrimaryKeySelective(customerApply);
		}
	}

	@Override
	public void recover(long id) {
		CustomerApply customerApply = new CustomerApply();
		customerApply.setId(id);
		this.customerApplyDao.updateByPrimaryKeySelective(customerApply);
	}

    @Override
    public void regiestCustomerApply(CustomerApply customerApply) {
        Long time = DateUtil.getTime();
        customerApply.setCheckStatus(CheckStatusEnum.WAIT.getValue());
        customerApplyDao.save(customerApply);
        Msg msg = new Msg();
        msg.setContent("你的审核申请已提交请耐心等待审核通过");
        msg.setSendCustomerId(1L);
        msg.setIsRead(0);
        msg.setSendTime(DateUtil.getTime());
        msg.setIsReceive(0);
        msg.setHandlerCustomerId(customerApply.getCustomerId());
        msgDao.save(msg);

    }
    //加入俱乐部审核
    @Override
    public void checkCustomerApply(CustomerApply customerApply) {
        StringBuffer msgs=new StringBuffer();
        CustomerApply selectCb =  customerApplyDao.getByPrimaryKey(customerApply.getId());
        if(!Objects.equals(selectCb.getCheckStatus(),CheckStatusEnum.WAIT.getValue())){
            throw new ServiceException("该申请已操作请不要重复操作");
        }
        if(Objects.equals(selectCb.getCheckStatus(),equals(CheckStatusEnum.NO.getValue()))){
            Msg msg = new Msg();
            msg.setContent(msgs.toString());
            msg.setSendCustomerId(null);
            msg.setIsRead(0);
            msg.setSendTime(DateUtil.getTime());
            msg.setIsReceive(0);
            msg.setHandlerCustomerId(selectCb.getCustomerId());
            msg.setContent(customerApply.getResaon());
            msgDao.save(msg);
            customerApplyDao.remove(selectCb);


        }
        CustomerInfo customerInfo = null;
        if(Objects.isNull(selectCb.getCustomerId())){//游客加入会员给会员权限
            User user = new User();
            String salt = CodeUtil.getUniqueCode();
            user.setSalt(salt);
            user.setUserName(selectCb.getPhone());
            user.setSalt(salt);
            user.setUserPwd(MD5Util.getMD5Pwd(salt, PropertiesUtil.getConfigProperty("user.resetPwd")));
            userDao.save(user);

            long time = DateUtil.getTime();
            Example ex = new Example(User.class);
            ex.createCriteria().andEqualTo("mobile", customerApply.getPhone());
            if (userDao.getCountByExample(ex) > 0) {
                throw new ServiceException("该手机号已注册");
            }
            Customer customer = new Customer();
            customer.setStatus(StatusEnum.NORMAL.getValue());
            customer.setCreateTime(time);
            customer.setModifyTime(time);
            customer.setUserId(user.getId());
            this.customerDao.save(customer);
            Car car = new Car();
            BeanUtils.copyProperties(customer,car,"id");
            existsName(car);
            car.setCustomerId(customer.getId());
            carDao.save(car);
             customerInfo = new CustomerInfo();
            BeanUtils.copyProperties(customer,customerInfo,"id");
            customerInfo.setCustomerId(customer.getId());
            customerInfoDao.save(customerInfo);

            UserRole userRole = new UserRole();//授权
              userRole.setClubId(customerApply.getClubId());
            userRole.setUserId(user.getId());
            userRole.setRoleId(Constant.MEMEBER_ROLE_ID);
            userRoleDao.save(userRole);

            CustomerClub customerClub = new CustomerClub();//绑定车和人的关系
            customerClub.setCustomerId(customer.getId());
            customerClub.setClubId(customerApply.getClubId());
            customerClubDao.save(customerClub);
        }else{//会员加入俱乐部 给会员权限
             Customer customer = customerDao.getByPrimaryKey(selectCb.getCustomerId());
             Example ex = new Example(CustomerInfo.class);
             ex.createCriteria().andEqualTo("customerId",customer.getId());
             customerInfo = customerInfoDao.getByExample(ex);
            if(Objects.isNull(customerInfo)){
                customerInfo = new CustomerInfo();
                BeanUtils.copyProperties(selectCb,customerInfo,"id");
                customerInfo.setCustomerId(customer.getId());
                customerInfoDao.save(customerInfo);
             }else{
                customerInfo = new CustomerInfo();
                BeanUtils.copyProperties(selectCb,customerInfo,"id");
                customerInfo.setCustomerId(customer.getId());
                customerInfoDao.updateByPrimaryKeySelective(customerInfo);
            }
            Car car = new Car();
            BeanUtils.copyProperties(selectCb,car,"id");
            existsName(car);
            car.setCustomerId(customer.getId());
            carDao.save(car);


            UserRole userRole = new UserRole();//授权
            userRole.setClubId(selectCb.getClubId());
            userRole.setUserId(customer.getUserId());
            userRole.setRoleId(Constant.MEMEBER_ROLE_ID);
            userRoleDao.save(userRole);
            CustomerClub customerClub = new CustomerClub();//绑定车和人的关系
            customerClub.setCustomerId(customer.getId());
            customerClub.setClubId(selectCb.getClubId());
            customerClubDao.save(customerClub);



        }
        Msg msg = new Msg();
        msg.setContent(msgs.toString());
        msg.setSendCustomerId(null);
        msg.setIsRead(0);
        msg.setSendTime(DateUtil.getTime());
        msg.setIsReceive(0);
        msg.setHandlerCustomerId(selectCb.getCustomerId());
        msg.setContent("入会成功");
        msgDao.save(msg);
        selectCb.setCheckStatus(CheckStatusEnum.YES.getValue());
        customerApplyDao.updateByPrimaryKey(selectCb);
    }

    @Override
    public CustomerApply getCheckWait(Long clubId) {
            return customerApplyDao.getCheckWait(clubId);

    }

    private void existsName(Car car) {
        Example ex =new Example(Car.class);
        Example.Criteria cr = ex.createCriteria();
        cr.andEqualTo("carNo", car.getCarNo());
        Car pojo = carDao.getByExample(ex);
        if (pojo != null && !pojo.getId().equals(car.getId())) {
            throw new ServiceException(car.getCarNo()+"该车牌号已存在");
        }

    }
}
